import { useEffect, useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { Layout } from "antd";

import { $ } from "@components/util";
import { session } from "@core";
import { getMenuItem } from "@routes/fullMenuConfig";

import FCInternalSider from "./components/FCInternalSider";
import FCInternalHeader from "./components/FCInternalHeader";
import FCInternalTabBar from "./components/FCInternalTabBar";
import FCInternalContent from "./components/FCInternalContent";
import FCInternalFooter from "./components/FCInternalFooter";

import styles from "./styles/main-frame.module.css";

import { Provider } from "@contexts/frame-context";
import {
  defaultNavigateMode,
  defaultCollapsed,
  defaultSiderWidth,
  defaultCollapsedSiderWidth,
  defaultHeaderHeight,
  defaultTabBarHeight,
  SessionKey,
} from "./constant/main-frame-constants";

const container_class = $(
  styles,
  "ant-design-pro",
  "ant-pro-basicLayout",
  "screen-xxl",
  "ant-pro-basicLayout-fix-siderbar",
  "ant-pro-basicLayout-mix"
);
const MainContent_class = $(styles, "ant-pro-content");

//
const findMenuItem = (items = [], keyPath = []) => {
  const queryKeyPath = [...keyPath];
  const queryKey = queryKeyPath.pop();
  const menuItem = items.find((item) => item.key === queryKey);
  if (menuItem?.children?.length > 0 && queryKeyPath?.length > 0) {
    return findMenuItem(menuItem.children, queryKeyPath);
  }
  return menuItem;
};

const findPage = (pages, key) => pages.find((page) => page.key === key);

const FCMainFrame = ({
  navigateMode = defaultNavigateMode,
  collapsed: initCollapsed = defaultCollapsed,
  siderWidth = defaultSiderWidth,
  collapsedSiderWidth = defaultCollapsedSiderWidth,
  headerHeight = defaultHeaderHeight,
  tabBarHeight = defaultTabBarHeight,
  menuItems = [],
}) => {
  const savedOpenedPages = session.get(SessionKey.openedPages);
  const savedActiveTabKey = session.get(SessionKey.activeTabKey);
  const savedOpenMenuKeys = session.get(SessionKey.openMenuKeys);
  const savedSelectedMenuItemKey = session.get(SessionKey.selectedMenuItemKey);

  const navigate = useNavigate();
  const { pathname } = useLocation();

  if (!savedOpenedPages) {
    console.log("need build open pages... location is:", pathname);
  }

  const [collapsed, setCollapsed] = useState(initCollapsed);
  const [openedPages, setOpenedPages] = useState(savedOpenedPages || []);
  const [activeTabKey, setActiveTabKey] = useState(savedActiveTabKey);
  const [openMenuKeys, setOpenMenuKeys] = useState(savedOpenMenuKeys || []);
  const [selectedMenuItemKey, setSelectedMenuItemKey] = useState(
    savedSelectedMenuItemKey
  );

  const currentSiderWidth = collapsed ? collapsedSiderWidth : siderWidth;

  /* private methods */
  //
  const openPage = (page) => {
    // menu
    if (page.keyPath) {
      setSelectedMenuItemKey(page.key);
      session.set(SessionKey.selectedMenuItemKey, page.key);
    }

    // tab
    setActiveTabKey(page.key);
    session.set(SessionKey.activeTabKey, page.key);

    // context
    navigate(page.route);
  };

  const handleOpenPage = ({key, keyPath}) => {
    const menuItem = findMenuItem(menuItems, keyPath);
    let page = findPage(openedPages, menuItem.key);
    if (!page) {
      page = {
        key,
        keyPath,
        title: menuItem.title,
        route: menuItem.route,
      };
      const newOpenedPages = [...openedPages, page];
      setOpenedPages(newOpenedPages);
      session.set(SessionKey.openedPages, newOpenedPages);
    }

    openPage(page);
  }

  const handleMenuItemClick = ({ key, keyPath }) => {
    handleOpenPage({key, keyPath})
    
  };

  const handleTabItemClick = (key) => {
    const page = findPage(openedPages, key);
    openPage(page);
  };

  const handleSetOpenMenuKeys = (keys) => {
    const currentOpenKeys = [[...keys].pop()];
    session.set(SessionKey.openMenuKeys, currentOpenKeys);
    setOpenMenuKeys(currentOpenKeys);
  };

  const handleTabItemRemove = (key) => {
    const pageIndex = openedPages.findIndex((item) => item.key === key);
    const lastPageIndex = Math.max(pageIndex - 1, 0);
    const pages = openedPages.filter((item, index) => index !== pageIndex);
    setOpenedPages(pages);
    session.set(SessionKey.openedPages, pages);

    // update active page
    if (key === activeTabKey && pages.length > 0) {
      const lastPage = pages[lastPageIndex];
      openPage(lastPage);
    }
  };

  function getFirstMenuInfo(menuInfo) {
    let menuItem;
    if (menuInfo && Array.isArray(menuInfo) && menuInfo.length > 0) {
      menuItem = menuInfo[0];
    }

    if (
      menuItem &&
      Array.isArray(menuItem.children) &&
      menuItem.children.length > 0
    ) {
      return getFirstMenuInfo(menuItem.children);
    }

    return menuItem;
  }

  function getMenuItemKeyPath(menuIetmKey) {
    const key = menuIetmKey;
    let keyPath = [];
    const parentKey = menuIetmKey.slice(0, 2) + "0000";
    keyPath = key === parentKey ? [key] : [key, parentKey];
    return { key, keyPath };
  }

  function listenPathname() {
    const menuItem = getMenuItem(menuItems, pathname)

    if (!Object.keys(menuItem).length) {
      setActiveTabKey('')
      session.set('activeTabKey', '')
    }
    
    const activeTabKey = session.get('activeTabKey')
    if (activeTabKey === menuItem?.key) return

    if (menuItem?.route) {
      const itemKeyPath = getMenuItemKeyPath(menuItem.key);
      handleOpenPage(itemKeyPath);
    }
  }

  useEffect(() => {
    if (!menuItems.length) return
    if (!openedPages.length) {
      const FirstMenuInfo = getFirstMenuInfo(menuItems);
      const itemKeyPath = getMenuItemKeyPath(FirstMenuInfo.key);
      handleMenuItemClick(itemKeyPath);
    }else {
      listenPathname()
    }
  }, [menuItems, pathname]);


  return (
    <Provider
      value={{
        navigateMode,
        collapsed,
        setCollapsed,
        siderWidth,
        collapsedSiderWidth,
        currentSiderWidth,
        headerHeight,
        tabBarHeight,
      }}
    >
      <div className={container_class}>
        <FCInternalSider
          menuItems={menuItems}
          onMenuItemClick={handleMenuItemClick}
          openKeys={openMenuKeys}
          setOpenKeys={handleSetOpenMenuKeys}
          selectedMenuItemKey={selectedMenuItemKey}
        />
        <Layout className={MainContent_class}>
          <FCInternalHeader />
          <FCInternalTabBar
            openedPages={openedPages}
            activeTabKey={activeTabKey}
            onTabItemClick={handleTabItemClick}
            onTabItemRemove={handleTabItemRemove}
          />

          <FCInternalContent />
          {/* <FCInternalFooter /> */}
        </Layout>
      </div>
    </Provider>
  );
};

export default FCMainFrame;
export { NavigateMode, WidthMode } from "./constant/main-frame-constants";
